import React, {
    Component,
} from 'react';

import {
    DeviceEventEmitter,
    View,
    ScrollView,
    Text,
    TextInput,
    Image,
    TouchableWithoutFeedback,
    BackHandler,
    Keyboard,
} from 'react-native';

import { connect } from 'react-redux';

import CXIcon from "../../components/cxicon/CXIcon";
import BackBottom from '../../routes/back';
import { getChatLog } from '../../actions/netease';
import { sendTxtMsg, UPDATECHATLOGCONTENT, APPENDCHATLOG } from '../../actions/msg';
import styles from './css/detail';

class ChatdetailScreen extends Component {
    static navigationOptions = ({ navigation }) => {
        let navigateOption = Object.assign(
            { 
                title: navigation.getParam('tnick', '未命名用户'),
            }, 
            BackBottom(), {
                headerRight:<View style={{paddingRight: 15}}><CXIcon name="mine_tab" size={18}></CXIcon></View>,
            }
        );
        return navigateOption;
    }

    constructor(props){
        super(props);
        this.state = {
            content: "",
            refresh_flg: false
        };
    }

    componentWillMount(){
        //返回键监听
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
        //键盘监听
        Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        Keyboard.addListener('keyboardDidHide', this._keyboardDidShow);
        //收到聊天消息
        DeviceEventEmitter.addListener('onMessage', (messageList) => this._receiveMessage(messageList));
    }

    _receiveMessage(messageList){
        for(let i=0; i<messageList.length; i++){
            let msg = Object.assign({}, messageList[i], {
              type: APPENDCHATLOG,
              fuid: messageList[i].uid
            });
            this.props.dispatch(msg);
        }
        this.setState({refresh_flg: !this.state.refresh_flg});
        this._keyboardDidShow();
    }

    componentDidMount() {
        let tuid = this.props.navigation.getParam("tuid", "0");
        getChatLog(tuid, (new Date()).valueOf(), (list) => {
            this.props.dispatch({
                type: UPDATECHATLOGCONTENT,
                tuid: tuid,
                lists: list
            });
            this.setState({refresh_flg: !this.state.refresh_flg});
            this._keyboardDidShow.bind(this);
        });
    }
    
    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
        Keyboard.removeListener('keyboardDidShow', this._keyboardDidShow);
        Keyboard.removeListener('keyboardDidHide', this._keyboardDidShow);
    }
    
    handleBackPress = () => {
        this.props.navigation.pop();
        return true;
    }

    _keyboardDidShow = () => {
        setTimeout(() => this._scroll.scrollToEnd(), 500);
    }

    _handleSend(){
        sendTxtMsg(this.props.fuid, this.props.navigation.getParam('tuid'), this.state.content, this.props.dispatch, () => {
            this.setState({
                content: ""
            });
            this._keyboardDidShow();
        });
    }

    render() {
        let tuid = this.props.navigation.getParam("tuid", "0");
        return (
            <View style={styles.container}>
                <ScrollView 
                    ref={(scroll)=>this._scroll = scroll}
                    contentContainerStyle={styles.contentContainer}
                    alwaysBounceVertical={true}
                    keyboardDismissMode="on-drag"
                >
                {this.props.chatlist[tuid].map((item,i) => {
                    return (
                        <View key={item.time} style={styles.chatItemBox}>
                            <View style={[styles.chatItemBodyBox, (item.uid == this.props.fuid ? styles.mine : styles.others)]}>
                                <View style={styles.avatarBox}>
                                    <Image style={styles.avatar} resizeMode="stretch" source={{uri: item.uid == this.props.fuid ? this.props.favatar : this.props.navigation.getParam('tavatar', '未命名用户')}} />
                                </View>
                                <View style={styles.chatItemContentBox}>
                                    <Text style={styles.chatItemContent}>{item.content}</Text>
                                </View>
                            </View>
                        </View>
                    )
                })} 
                </ScrollView>
                <View style={styles.textBox}>
                    <TextInput
                        placeholder="你和TA说点什么？"
                        placeholderTextColor="#c4c4c4"
                        autoCorrect={false}
                        style={styles.input}
                        multiline={true}
                        onChangeText={(content) => this.setState({content})}
                        value={this.state.content}
                        onSubmitEditing={Keyboard.dismiss}
                    />
                {this.state.content ?
                    <TouchableWithoutFeedback
                        onPress={() => this._handleSend()}
                    >
                        <Text style={styles.sendBtn}>发送</Text>
                    </TouchableWithoutFeedback>
                : null}
                </View>
                <View style={styles.funcBox}>
                    <Text>这是功能区</Text>
                </View>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
      fuid: state.user.uid,
      favatar: state.user.avatar,
      chatlist: state.chatlog.list
    }
  }
  
  export default connect(mapStateToProps)(ChatdetailScreen);